package cn.edu.kzjsxy.graduationproject.tool;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 阿里云上传图片工具类
 * @author acer
 */
@Component
public class AliOSSUtils {

	@Value("${aliyun.oss.endpoint}")
	private String endpoint;

	@Value("${aliyun.oss.accessKeyId}")
	private String accessKeyId;

	@Value("${aliyun.oss.accessKeySecret}")
	private String accessKeySecret;

	@Value("${aliyun.oss.bucketName}")
	private String bucketName;

	@Value("${aliyun.oss.connectionTimeout}")
	private int connectionTimeout;  // 最大连接等待时间

	/**
	 * 实现上传文件到 OSS
	 */
	public String upload(MultipartFile file) throws IOException {
		// 获取文件名和后缀
		String fileName = System.currentTimeMillis() + getFileExtension(file.getOriginalFilename());
		// 创建文件输入流
		InputStream inputStream = file.getInputStream();
		ClientBuilderConfiguration config = new ClientBuilderConfiguration();
		config.setConnectionTimeout(connectionTimeout);  // 设置连接超时时间
		// 上传文件到 OSS
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, config);
		ossClient.putObject(bucketName, fileName, inputStream);
		// 生成文件访问路径
		String url = generateFileUrl(bucketName, endpoint, fileName);
		// 关闭 ossClient 和输入流
		ossClient.shutdown();
		inputStream.close();
		return url;  // 返回上传到 oss 的路径
	}

	// 删除存储内容并保存新的存储内容
	public String deleteAndSaveNewFile(String objectName, MultipartFile newFile) throws IOException {
		//	截取出文件名
		objectName = extractFileNameFromUrl(objectName);
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		// 删除存储内容
		if(!objectName.contains("默认头像")){
			ossClient.deleteObject(bucketName, objectName);
		}
		// 保存新的存储内容
		String newFileName =System.currentTimeMillis() + getFileExtension(newFile.getOriginalFilename());
		InputStream inputStream = newFile.getInputStream();
		ossClient.putObject(bucketName, newFileName, inputStream);
		String url = generateFileUrl(bucketName, endpoint, newFileName);

		// 关闭 ossClient 和输入流
		ossClient.shutdown();
		inputStream.close();

		return url;
	}

	// 从URL中截取文件名称
	public String extractFileNameFromUrl(String fileUrl) {
		if (fileUrl != null && !fileUrl.isEmpty()) {
			// 以"/"作为分隔符，获取路径的最后一部分
			String[] parts = fileUrl.split("/");
			if (parts.length > 0) {
				return parts[parts.length - 1];
			} else {
				return "";
			}
		} else {
			return "";
		}
	}


	/**
	 * 获取文件的后缀名
	 */
	private String getFileExtension(String fileName) {
		if (fileName!= null && fileName.contains(".")) {
			return fileName.substring(fileName.lastIndexOf("."));
		} else {
			return "";
		}
	}

	/**
	 * 生成文件访问路径的辅助方法
	 */
	private String generateFileUrl(String bucketName, String endpoint, String fileName) throws MalformedURLException {
		// 添加协议部分
		String protocol = "http";  // 或者 "https"
		String urlStr = protocol + "://" + bucketName + "." + endpoint + "/" + fileName;
		URL url = new URL(urlStr);
		return url.toString();
	}
}
